package com.wsp.controllermanagement.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wsp.apimanagement.pojo.dto.Result;
import com.wsp.apimanagement.pojo.entity.User;
import com.wsp.apimanagement.service.UserService;
import com.wsp.service.util.RedisUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.concurrent.TimeUnit;

/**
 * Package: com.wsp.controllermanagement.controller
 * Description： TODO
 *
 * @Author: 巫思平
 * Copyright: Copyright (c) 2020
 * Version: 1
 */
@Api(tags = "用户请求接口")
@RestController
@RequestMapping("/user")
@ConfigurationProperties("wsp.web.wx.config")
public class UserController {
    private String appId;
    private String appSecret;
    private String wxUrl;
    @Autowired
    private UserService userService;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private RestTemplate restTemplate;
    /**
     * 微信授权登录
     */
    @ApiOperation(value = "用户进行微信登录", notes = "返回用户信息，包括openid")
    @GetMapping("/wxLogin")
    public Result<User> wxLogin(
            @RequestParam("code") String code,
            @RequestParam("nickName") String nickName,
            @RequestParam("avatar") String avatar
    ){
        String requestUrl = wxUrl + "?appid=" + appId +
                "&secret=" + appSecret + "&js_code=" + code +
                "&grant_type=" + "authorization_code";
        String result = restTemplate.getForObject(requestUrl,String.class);
        JSONObject object = JSON.parseObject(result);
        String openId = object.getString("openId");
        String sessionKey = object.getString("session_key");
        if(redisUtil.get(openId)==null&&(openId!=null&&sessionKey!=null)){
            redisUtil.set(openId,sessionKey,6000, TimeUnit.SECONDS);
        }
        Result<User> user = userService.findUserByOpenId(openId);
        // 用户第一次登录小程序
        if(user==null){
            user = userService.insertUser(openId,nickName,avatar);
        }
        return user;
    }

    public void setAppId(String appId) {
        this.appId = appId;
    }

    public void setAppSecret(String appSecret) {
        this.appSecret = appSecret;
    }

    public void setWxUrl(String wxUrl) {
        this.wxUrl = wxUrl;
    }
}
